package com.cyf.cheyichong.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyf.cheyichong.commonutils.R;
import com.cyf.cheyichong.entity.Jack;
import com.cyf.cheyichong.service.JackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
public class JackController {
    Boolean wechat = false;

    @Autowired
    private JackService jackService;

    @GetMapping("/hello")
    public R Hello() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("indexes", 6);
        map.put("time", 3 * 60 * 60);
        return R.ok().data(map);
    }

    //    获取所有插座的信息
    @GetMapping("/all/jacks")
    public R findAllJacks() {
        List<Jack> jackList = jackService.list();
        return R.ok().data("jacks", jackList);
    }

    //    微信返回支付成功的消息
    @GetMapping("/wechat")
    public void wechatPaySuccess() {
        wechat = true;
    }

    //    获取到微信支付成功的消息，此时再去数据库查询各插孔的状态
    @GetMapping("/check/jacks")
    public R checkJacks() {
        if (wechat) {
            wechat = false;
//            构建条件：数据库中 在使用的、未到期 的充电桩
            QueryWrapper<Jack> wrapper = new QueryWrapper<>();
            wrapper.eq("is_used", 1);
            wrapper.gt("stop_time", new Date());
//            从数据库查询插孔状态并返回
            List<Jack> jacks = jackService.list(wrapper);
//            构建返回数据
            ArrayList<Object> maps = new ArrayList<>();
            for (Jack jack : jacks) {
                Integer jackId = jack.getJackId();
                Date stopTime = jack.getStopTime();
                long time = stopTime.getTime() - new Date().getTime();
                HashMap<String, Object> map = new HashMap<>();
                map.put("jackId", jackId);
                map.put("time", time);
                maps.add(map);
            }
            return R.ok().data("jacksInfo", maps);
        }
        return R.error().message("无新可用插座");
    }
}
